<?php
/**
 * Created by PhpStorm.
 * User: Argon
 * Date: 2016/12/16
 * Time: 10:19
 */

namespace Admin\Controller;


use Think\Controller;

class RoleController extends Controller
{
    private $_model;

    protected function _initialize() {
        $this->_model = D('Role');
    }
    private function _before_view() {
        $permissions = D('Permission')->getList();
        $this->assign('permissions', json_encode($permissions));
    }

    public function index($keyword=""){
        $keyword=trim($keyword);
        $cond=[];
        if($keyword){
            $cond['name']=['like',"%{$keyword}%"];
        }

        $this->assign($this->_model->getPageResult($cond));
        $this->display();
    }
    public function add(){
        if(IS_POST){
            if($this->_model->create()==false){
                $this->error(listError($this->_model));
            }
            if($this->_model->addRole()===false){
                $this->error(listError($this->_model));
            }
            $this->success("添加成功",U("index"));
            exit;
        }
        $this->_before_view();
        $this->display();
    }

    public function edit($id) {
        if (IS_POST) {
            if ($this->_model->create() === false) {
                $this->error(get_error($this->_model));
            }
            if ($this->_model->saveRole($id) === false) {
                $this->error(get_error($this->_model));
            }
            $this->success('修改成功', U('index'));
        } else {
            $row = $this->_model->getRoleInfo($id);
            $this->assign('row', $row);
            $this->_before_view();
            $this->display('add');
        }
    }
    
    public function remove($id) {
        if(($res=$this->_model->remove($id))==false){
            $this->error(listError($this->_model));
        }
        $this->success("删除成功",U("index"));
    }
}